package com.dmzapp.api.servlet;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dmzapp.api.cache.local.LocalCache;
import com.dmzapp.api.util.Constant;
import com.dmzapp.api.util.StringUtils;
import com.dmzapp.api.vo.AppInfo;
import com.dmzapp.api.vo.DmzEnv;

/**
 * 
 * 根据条件获取applist Servlet implementation class for Servlet: AppListRequestHandler
 * 
 */
public class AppListRequestHandler extends DMZSerlvet implements javax.servlet.Servlet {
    static final long serialVersionUID = 1L;
    private ObjectMapper mapper = new ObjectMapper();
    Logger logger = LoggerFactory.getLogger("dmzlog");
    @Override
    protected void handle(HttpServletRequest request, HttpServletResponse response) {
        try {
            String version = request.getParameter("v_code");
            int clientVersionCode = 0;
            if (version != null) {
                clientVersionCode = Integer.valueOf(version);
            }
            int start = Integer.valueOf(request.getParameter("start"));
            String pagesize =request.getParameter("num");
            int num = Constant.APP_LIST_PAGE_SIZE;
            if (!StringUtils.isNullOrEmpty(pagesize)) {
                num = Integer.valueOf(pagesize);
            }
            
            Map<String, Object> responseMap = new HashMap<String, Object>();

            // 3 通过appid set，获取本地的app信息
            List<AppInfo> appListResponse = new ArrayList<AppInfo>();
            for (AppInfo app : LocalCache.getInstance().appCache.values()) {
                AppInfo newapp = new AppInfo(app, clientVersionCode);
                
                if (clientVersionCode < 5 && newapp.getCustom_active() == 1) {
                    //如果是低版本，则不会将需要注册的app传过去
                } else {
                    appListResponse.add(newapp);
                }
            }
            logger.debug("appListResponse: " + (appListResponse == null ? null : appListResponse.size()));
            int total = appListResponse.size();
            int end = total - start < num ? total : start + num;
            
            responseMap.put("applist", appListResponse.subList(start, end));
            responseMap.put("dmzenv", new DmzEnv());
            responseMap.put("listSize", total);
            responseMap.put("server_time", Calendar.getInstance().getTimeInMillis());
            
            mapper.writeValue(response.getWriter(), responseMap);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}